<template>
    <div>
        <!-- 网页头部 -->
        <el-card class="head-card">
            <i class="el-icon-s-fold"></i><span style="font-size: 18px">大健康综合管理后台</span>

            <h2 style="color: black">订单管理</h2>
        </el-card>

        <!-- 网页中部 -->
        <el-card class="body-card">
            <h4 style="margin-top: 0">查询条件</h4>
            <el-form :inline="true" :model="condition" class="demo-form-inline">
                <el-form-item label="订单编号">
                    <!--模糊查询-->
                    <el-input
                            placeholder="请输入内容"
                            v-model="condition.orderNumber"
                            clearable>
                    </el-input>

                </el-form-item>

                <el-form-item label="用户id">
                    <el-autocomplete
                            class="inline-input"
                            v-model="condition.state1"
                            :fetch-suggestions="querySearch"
                            placeholder="请输入内容"
                            @select="handleSelect"
                    ></el-autocomplete>
                </el-form-item>

                <el-form-item label="订单状态">
                    <el-select v-model="value" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetting">重置</el-button>
                    <el-button type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 网页底部 -->
        <el-card class="foot-card">
            <span>

                <el-button type="warning"
                           style="padding-left: 35px; padding-right: 35px;  margin-right:30px ">合并订单</el-button>

                <el-button type="primary" @click="showAddDialog"
                           style="padding-left: 35px; padding-right: 35px;  margin-right:30px ">打印快递模板</el-button>
                <el-button type="success" @click="exportExcel" icon="el-icon-s-flag" size="medium"
                           style="padding-left: 35px; padding-right: 35px;  margin-right:30px ">导出Excel</el-button>

            </span>
            <template>

                <el-table :data="tableData" style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>

                    <el-table-column prop="orderNumber" label="订单编号"></el-table-column>

                    <el-table-column prop="amount" label="订单金额"></el-table-column>

                    <el-table-column prop="createTime" label="下单时间"></el-table-column>

                    <el-table-column prop="userId" label="用户ID"></el-table-column>

                    <el-table-column prop="orderSource" label="订单来源"></el-table-column>

                    <el-table-column prop="paymentMethod" label="支付方式"></el-table-column>

                    <el-table-column prop="state" label="订单状态"></el-table-column>

                    <el-table-column label="操作">
                        <template slot-scope="scope">

                            <el-button @click="viewOrder(scope.$index, scope.row)" type="text">查看订单</el-button>

                            <el-button @click="closeOrder(scope.$index, scope.row)" type="text">关闭订单</el-button>

                        </template>

                    </el-table-column>

                </el-table>

            </template>
            <!-- 分页 -->
            <el-pagination style="margin-top: 10px;"
                           background
                           :page-sizes="[5, 10, 20]"
                           :page-size="pageBean.size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pageBean.count"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="pageBean.current">
            </el-pagination>

            <el-dialog title="新增权限" :visible.sync="dialogFormVisible">

                <!--            新增权限的表单-->
                <el-form :model="expressForm" ref="expressForm" label-width="formLabelWidth">

                </el-form>

                <span slot="footer" class="dialog-footer">
                <el-button @click="cancelForm">取 消</el-button>
                <el-button type="primary" @click="saveOrUpdate">打印</el-button>
            </span>

            </el-dialog>


        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Order ",
        data() {
            return {
                dialogFormVisible: false,
                restaurants: [],



                options: [
                    {
                        value: '选项1',
                        label: '黄金糕'
                    }, {
                        value: '选项2',
                        label: '双皮奶'
                    },
                ],
                value: '',

                categoryNameList: [],
                pickerOptions: {},

                condition: {
                    name: '',
                    orderNumber: '',
                    userId: '',
                    state: '',
                    orderSource: '',
                    startDate: '',
                    endDate: '',

                    state1: '',
                    begin: "",
                    end: "",
                    page: 1,
                    size: 5
                },
                pageBean: {},

                pageNum: 1,
                pageSize: 5,
                total: 0,
                //表格数据
                tableData: [],
                //复选框
                multipleSelection: []
            }
        },

        methods: {
            // 点击添加，打开添加页面
            showAddDialog() {
                this.expressForm = {}
                this.dialogFormVisible = true;
            },


            //导出Excel
            exportExcel() {
                const url = '/order/export';
                this.$axios.get(url)
                    .then(response => {
                        const blob = response.data;
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = 'orders.xlsx';
                        document.body.appendChild(link);
                        link.click();
                    })
                    .catch(error => {
                        console.error('导出Excel失败：', error);
                        // 根据您的需求处理错误
                    });
            },
            //上传成功
            handleSuccess(resp) {
                this.$message.success(resp);
                //重新加载数据
                // this.findByPage();
            },

            querySearch(queryString, cb) {
                let restaurants = this.restaurants;
                let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) {
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            loadAll() {
                return [
                    {"value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号"},
                    {"value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号"},
                    {"value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113"},
                ]
            },
            handleSelect(item) {
                console.log(item);
            },


            search() {
                // 将查询条件封装到请求体中
                let orderQueryVo = this.condition;
                console.log('orderQueryVo', orderQueryVo)
                // debugger;

                // 发起请求
                this.$axios.post('/order/findByCondition', {
                    name: orderQueryVo.name,
                    categoryId: orderQueryVo.categoryId,
                    status: orderQueryVo.status,
                    code: orderQueryVo.code,
                    lowPrice: orderQueryVo.lowPrice,
                    highPrice: orderQueryVo.highPrice,
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                }).then(resp => {
                    console.log("查询成功", resp);

                    this.total = resp.data.data.total;
                    this.tableData = resp.data.data.records;
                })

            },

            fetchData() {
                this.$axios.get('/api/orders') // 替换为你的后端API地址
                    .then(response => {
                        this.tableData = response.data;
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            async viewOrder(index, row) {
                // 发送异步请求到后端，获取订单项信息

                const response = await axios.get(`/api/getItemByOrderId/${row.orderId}`);
                const orderItems = response.data; // 获取返回的订单项数据
                // 这里可以根据实际情况将订单项数据传递给OrderDetails页或者其他处理逻辑
                // ...
                // 跳转到OrderDetails页
                this.$router.push({ path: '/order/details', query: { orderId: row.orderId, orderItems: orderItems } });
            },

            closeOrder(index, row) {
                // 这里可以编写关闭订单的逻辑，例如通过弹窗确认后调用后端API关闭订单等。
                console.log('关闭订单', index, row);
            },


            // search() {
            //     if (this.condition.categoryName == '' && this.condition.begin == '' && this.condition.end == '') {
            //         this.$message.warning("请输入搜索条件");
            //         return;
            //     }
            //     this.pageNum = 1;
            //     this.findByCondition();
            // },

            findByCondition() {
                this.$axios.post(`/category/findByCondition`, this.condition).then(resp => {
                    console.log('resp', resp)
                    this.pageBean = resp.data;
                    this.tableData = this.pageBean.list;

                });
            },
            findAllCategoryName() {
                this.$axios.get('/category/findAllCategoryName').then(resp => {
                    // 将服务器返回的数据解析并赋值给 options 数组
                    this.categoryNameList = resp.data.data;
                }).catch(error => {
                    console.error(error);
                });
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            resetting() {
                this.condition.page = 1;
                this.condition.size = 5;
                this.condition.categoryName = '';
                this.condition.begin = '';
                this.condition.end = '';
                this.findByCondition();
            },
            onSubmit() {
                console.log('submit!');
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.reloadData();
            },
            handleCurrentChange(val) {
                this.pageNum = val;
                this.reloadData();
            },

            reloadData() {
                this.$axios.get("/order/findAll", {
                    params: {
                        pageSize: this.pageSize,
                        pageNum: this.pageNum,
                        // name: this.name
                    }
                }).then(res => {
                    console.log("", res);
                    this.total = res.data.data.total;
                    this.tableData = res.data.data.records;
                })
            },

            dateFormatter(row, column, cellValue) {

                // 将时间戳转换为可读格式
// 将时间戳转换为可读格式
                let date = new Date(cellValue);
                let year = date.getFullYear();
                let month = ("0" + (date.getMonth() + 1)).slice(-2);
                let day = ("0" + date.getDate()).slice(-2);
                let hours = ("0" + date.getHours()).slice(-2);
                let minutes = ("0" + date.getMinutes()).slice(-2);
                let seconds = ("0" + date.getSeconds()).slice(-2);
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

            },


        }, created() {
            // this.fetchCategories();
            this.reloadData();
            // this.findByCondition();
            // this.search();
            // this.findAllCategoryName();
            this.restaurants = this.loadAll();
        },
    }
</script>

<style scoped>
    .head-card {
        text-align: left;
        height: 200px;

    }

    .el-icon-s-fold {
        font-size: 23px;
        margin-right: 10px;
        margin-bottom: 40px;
    }

    .body-card {
        text-align: left;
        padding-left: 18px;
        width: 90%;
        display: block;
        margin: 30px auto;
        height: 130px;
        padding-bottom: 20px;
    }

    .foot-card {
        text-align: left;
        padding-left: 18px;
        width: 90%;
        display: block;
        margin: 0 auto;
    }

    .el-button {

    }
</style>